package com.ai.util;

import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.Arrays;

public class StringUtil {

    public static String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    public static void printHexString(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            System.out.print(hex.toUpperCase());
        }

    }

    public static short[] bytesToShort(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        short[] shorts = new short[bytes.length / 2];
        ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
        return shorts;
    }

    public static byte[] shortToBytes(short shorts) {

        byte[] bytes = new byte[2];
        ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(shorts);

        return bytes;
    }

    public static byte[] intToByteArray(int src, int length)
    {
        byte[] b = new byte[length];
        for (int i = 0; i < length; i++)
        {
            b[length - i - 1] = (byte)((src >> 8 * i) & 0xff);
        }
        return b;

    }


    public static String convertHexToNumeric(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] == 0)
                continue;
            int numericValue = Character.getNumericValue(bytes[i]);
            if (numericValue == -1) {
                sb.append(0);
            } else {
                sb.append(numericValue);
            }
        }
        return sb.toString();
    }



    public static byte[] convertStringToHex(String str,int length) {
        if (str == null){
            str = "";
        }
        if (str.length() == length) {
            return str.getBytes(StandardCharsets.US_ASCII);
        }
        StringBuilder sb = new StringBuilder(str);
        // 如果原始字符串长度小于目标长度
        while (sb.length() < length) {
            sb.append((char) 0);  // 添加 null 字符（ASCII 0）
        }
        return sb.toString().getBytes(StandardCharsets.US_ASCII);
    }
    
    // 转换字符串为十六进制字节数组
//    public static byte[] convertStringToHex(String str, int length) {
//        if (str.length() != length) {
//            // 使用空格填充至指定长度
//            str = String.format("%-" + length + "s", str);
//        }
//        // 将每个字符转换为对应的 ASCII 十六进制字节
//        byte[] byteArray = new byte[str.length()];
//
//        for (int i = 0; i < str.length(); i++) {
//            // 直接将字符转为字节（ASCII）
//            byteArray[i] = (byte) str.charAt(i);
//        }
//
//        return byteArray;
//    }
    public static byte[] convertBigDecimalToHex(BigDecimal value, int totalLength, int decimalPlaces) {
        // 将小数点右移，按整数处理
        BigDecimal scaledValue = value.movePointRight(decimalPlaces);

        // 先把值转换为字符串// 去掉科学计数法
        String formattedValue = scaledValue.toPlainString();

        // 填充零，保留整数部分+小数部分
        String paddedValue = String.format("%0" + totalLength + "d", Long.parseLong(formattedValue.replace(".", "")));

        // 处理小数点位置
//        if (decimalPlaces > 0) {
//            paddedValue = paddedValue.substring(0, paddedValue.length() - decimalPlaces) + "." + paddedValue.substring(paddedValue.length() - decimalPlaces);
//        }

        // 转换为字节数组，使用 ASCII 编码
        return paddedValue.getBytes(StandardCharsets.US_ASCII);
    }

    // 测试
//    public static void main(String[] args) {
//        BigDecimal value = new BigDecimal("1.1");  // 测试 BigDecimal 值
//        int totalLength = 12;  // 总长度为6
//        int decimalPlaces = 3;  // 小数位为3
//
//        byte[] result = convertBigDecimalToHex(value, totalLength, decimalPlaces);
//
//        // 打印字节数组的内容（以可打印字符的形式输出）
//        System.out.println(new String(result, StandardCharsets.US_ASCII));
//    }

    /**
     *  生成重复字符的字符串
     * @param length
     * @param ch
     * @return
     */
    public static String generateRepeatingChars(int length, char ch) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(ch);
        }
        return sb.toString();
    }
    public static byte[] byteInsert(byte[] sourceBytes, byte[] insertBytes, int start) {
        for (int i = 0; i < insertBytes.length; i++) {
            sourceBytes[start + i] = insertBytes[i];
        }


        return sourceBytes;
    }

    public static float getFloat(byte[] bytes) {
        return Float.intBitsToFloat(getInt(bytes));
    }

    public static int getInt(byte[] bytes) {
        return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & (bytes[2] << 16)) | (0xff000000 & (bytes[3] << 24));
    }

    public static byte[] charToByte(char c) {
        byte[] b = new byte[2];
        b[0] = (byte) ((c & 0xFF00) >> 8);
        b[1] = (byte) (c & 0xFF);
        return b;
    }

    public static byte[] byteMerger(byte[] bt1, byte[] bt2) {
        byte[] bt3 = new byte[bt1.length + bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }


    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[2];
//        result[0] = (byte) ((i >> 24) & 0xFF);
//        result[1] = (byte) ((i >> 16) & 0xFF);
        result[0] = (byte) ((i >> 8) & 0xFF);
        result[1] = (byte) (i & 0xFF);
        return result;
    }


    //將10進制轉換為16進制
    public static String encodeHEX(Integer numb) {
        String hex = Integer.toHexString(numb);
        return hex;
    }


    public static byte[] hexStrToBinaryStr(String hexString) {
        if (hexString.isEmpty()) {
            return null;
        }
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;
        byte[] bytes = new byte[len / 2];
        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }
        return bytes;
    }


    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 字节转换为浮点
     *
     * @param b     字节（至少4个字节）
     * @param index 开始位置
     * @return
     */
    public static float byte2float(byte[] b, int index) {
        int l;
        l = b[index + 0];
        l &= 0xff;
        l |= ((long) b[index + 1] << 8);
        l &= 0xffff;
        l |= ((long) b[index + 2] << 16);
        l &= 0xffffff;
        l |= ((long) b[index + 3] << 24);
        return Float.intBitsToFloat(l);
    }

}
